package com.cloudcc.mobile.util;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.support.v4.app.NotificationCompat;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Toast;

import com.cloudcc.cloudframe.util.LogUtils;
import com.cloudcc.mobile.AppContext;
import com.cloudcc.mobile.R;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;

/**
 * 通用工具类
 * 
 * @author wangzhiqiang
 * @date 2015-6-8 上午9:06:08
 * 
 */
public class Tools {
	// 加密 解密
	static {
		System.loadLibrary("hello-jni");
	}

	public native static byte enCrypt(byte data);

	public native static byte deCrypt(byte data);

	/**
	 * 获取解密密钥
	 * 
	 * @return
	 */
	public native static String getpassword();

	/**
	 * 获取文件的绝对路径
	 * 
	 * @param files
	 * @return
	 */
	public static String getImagePath(String files) {
		String state = Environment.getExternalStorageState();
		LogUtils.d("bug", "state:" + state);
		File file = Environment.getExternalStorageDirectory();
		File file2 = new File(file.getAbsolutePath() + files);
		if (!file2.exists()) {
			file2.mkdirs();
		}
		if (state.equals(Environment.MEDIA_MOUNTED)) {
			return file2.getAbsolutePath();
		} else {
			return "";
		}
	}

	/**
	 * 获取一个字符串中第几个符号的位置
	 * 
	 * @param string
	 * @param search
	 * @param num
	 * @return
	 */
	public static int getCharacterPosition(String string, String search, int num) {
		// 这里是获取"/"符号的位置
		Matcher slashMatcher = Pattern.compile(search).matcher(string);
		int mIdx = 0;
		while (slashMatcher.find()) {
			mIdx++;
			// 当"/"符号第三次出现的位置
			if (mIdx == num) {
				break;
			}
		}
		return slashMatcher.start();
	}

	/**
	 * 获取随机数子
	 * 
	 * @return
	 */
	public static int getNum() {
		long a = System.currentTimeMillis();
		String c = String.valueOf(a);
		int b = Integer.valueOf(c.substring(c.length() - 5, c.length()));
		return b;
	}

	/**
	 * 获取字体大小
	 * 
	 * @param context
	 * @param textSize
	 * @return
	 */
	public static int getFontSize(Context context) {
		DisplayMetrics dm = new DisplayMetrics();
		WindowManager windowManager = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);
		windowManager.getDefaultDisplay().getMetrics(dm);
		int screenHeight = dm.heightPixels;
		int screenWeigth = dm.widthPixels;
		// screenWidth = screenWidth > screenHeight ? screenWidth :
		// screenHeight;
		if (screenWeigth <= 480) {
			return 16;
		} else if (480 < screenWeigth && screenWeigth <= 720) {
			return 17;
		} else {
			return 18;
		}

	}

	/**
	 * 转换时间格式
	 */
	@SuppressLint("SimpleDateFormat")
	public static String getTime(long time) {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = new Date(time);
		return formatter.format(date);
	}

	/**
	 * 转换时间格式
	 */
	@SuppressLint("SimpleDateFormat")
	public static String getTime3(long time) {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
		Date date = new Date(time);
		return formatter.format(date);
	}

	/**
	 * 获取当前网络时间
	 */
	@SuppressLint("SimpleDateFormat")
	public static String getNowTime() {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		formatter.setTimeZone(TimeZone.getTimeZone("GMT+8"));
		return formatter.format(new Date());
	}

	/**
	 * 将短时间格式时间转换为字符串 yyyy-MM-dd
	 * 
	 */
	public static String getYMDTime(long time) {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		Date date = new Date(time);
		String dateString = formatter.format(date);
		return dateString;
	}

	public static String getTime2(long time) {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		Date date = new Date(time);
		return formatter.format(date);
	}

	public static String getTimeName(long time) {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
		Date date = new Date(time);
		return formatter.format(date);
	}

	/**
	 * 获取字符串的长度，中文占一个字符,英文数字占半个字符
	 * 
	 * @param value
	 *            指定的字符串
	 * @return 字符串的长度
	 */
	/**
	 * 得到字符串长度
	 * 
	 * @param text
	 * @return
	 */
	public static int length(String text) {
		String Reg = "^[\u4e00-\u9fa5]{1}$";
		int result = 0;
		for (int i = 0; i < text.length(); i++) {
			String b = Character.toString(text.charAt(i));
			if (b.matches(Reg))
				result += 2;
			else
				result++;
		}
		return result;
	}

	/**
	 * 判别是不是数字
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isNum(String str) {
		Pattern pattern = Pattern.compile("[0-9]*");
		return pattern.matcher(str).matches();
	}

	/**
	 * 打印错误日志
	 * 
	 * @param e
	 */
	public static void handle(Exception e) {
		if (AppContext.isDebug) {
			e.printStackTrace();
			// TODO 出现的问题主动上报
			// CrashHandler.getInstance().uncaughtException(paramThread,
			// paramThrowable)
		}
	}

	/**
	 * 电话号码验证
	 * 
	 * @param phoneNumber
	 *            手机号码
	 * @return
	 */
	public static boolean isPhoneNumber(String phoneNumber) {
		Pattern pattern = Pattern
				.compile("((^(13|15|18)[0-9]{9}$)|(^0[1,2]{1}\\d{1}-?\\d{8}$)|(^0[3-9] {1}\\d{2}-?\\d{7,8}$)|(^0[1,2]{1}\\d{1}-?\\d{8}-(\\d{1,4})$)|(^0[3-9]{1}\\d{2}-? \\d{7,8}-(\\d{1,4})$))");
		Matcher m = pattern.matcher(phoneNumber);
		return m.matches();
	}

	/**
	 * 邮箱验证
	 * 
	 * @param mail
	 *            邮箱
	 * @return
	 */
	public static boolean isEmail(String mail) {
		Pattern pattern = Pattern
				.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
		Matcher m = pattern.matcher(mail);
		return m.matches();
	}

	/**
	 * 判断是否是空
	 */
	public static boolean isNull(String str) {
		if (str.equals(" , ") || str.equals(", ") || str.equals(",")
				|| str == "[]" || str == null || str == "<null>"
				|| "<null>".equals(str) || null == str || "".equals(str)
				|| " ".equals(str) || "null".equals(str)
				|| str.equals("NetworkError")) {
			return true;
		}
		return false;
	}

	/**
	 * 吐司对话框
	 * 
	 * @param context
	 * @param info
	 */
	public static void showInfo(Context context, String info) {
		Toast.makeText(context, info, 1).show();
	}

	/**
	 * 日志打印
	 */
	public static void i(String tag, String msg) {
		if (AppContext.isDebug) {
			Log.i(tag, msg);
		}
	}

	public static String subAddress(String addresss){
		if(addresss == null || addresss.length() == 0){
			return addresss;
		}
		String addressSub;
		int end = addresss.length();
		if(addresss.indexOf("街") > 0){
			end = addresss.indexOf("街")+1;
		}if(addresss.indexOf("道") > 0){
			end = addresss.indexOf("道")+1;
		}if(addresss.indexOf("路") > 0){
			end = addresss.indexOf("路")+1;
		}

		addressSub = addresss.substring(0,end);

		return addressSub;
	}

	public static void i(String tag, long msg) {
		i(tag, String.valueOf(msg));
	}

	public static void i(String tag, int msg) {
		i(tag, String.valueOf(msg));
	}

	public static void i(String tag, boolean msg) {
		i(tag, String.valueOf(msg));
	}

	//消息通知
	public static void notifacation(Context context , String name, Intent myintent,
							 String showmsg) {

		NotificationManager manager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);

		PendingIntent contentIntent = PendingIntent.getActivity(context, 1,
				myintent, PendingIntent.FLAG_UPDATE_CURRENT);

		NotificationCompat.Builder builder = new NotificationCompat.Builder(
				context)
				.setSmallIcon(R.drawable.icon)
				.setContentTitle(name)
				.setContentText(showmsg)
				.setTicker("亲，来消息了")
				.setAutoCancel(true)
				.setContentIntent(contentIntent)
				.setDefaults(Notification.DEFAULT_LIGHTS);

		// 发送通知
		manager.notify(1000, builder.build());
	}

	//判断是否存在google服务
	public static boolean isGooglePlayServiceAvailable (Context context) {
		int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(context);
		if (status == ConnectionResult.SUCCESS) {
			return true;
		} else {
			return false;
		}
	}


	/**
	 * 判断国家是否是国内用户
	 *
	 * @return
	 */
	public static boolean isCN(Context context) {
		TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
		String countryIso = tm.getSimCountryIso();
		boolean isCN = false;//判断是不是大陆
		if (!TextUtils.isEmpty(countryIso)) {
			countryIso = countryIso.toUpperCase(Locale.US);
			if (countryIso.contains("CN")) {
				isCN = true;
			}
		}else{
			isCN = true;
		}
		return isCN;

	}

}
